
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { getSearchList, getSearchSuggest, getSearchResult, getOptionsData, recommend } from "@/api/home"
import { type search, type searchSuggest, type searchResult, type parpams, type TotalOptions, type parameter, type Recommend } from '@/typings'
import { LoadingBar, Dialog } from '@varlet/ui'
import _ from 'lodash'
import { SearchHistory } from '@/stores/total'
const sethistory = SearchHistory()
const selectOneValue = ref("综合")
const active = ref(0)
const sort = ref("升序")
const right = ref(false)
const size = ref<number>(20)
const oldData = ref<searchResult>()

const loading = ref(false)
const finished = ref(false)
const scorll = ref()
const son = ref()
const flag = ref<boolean>(false)
const activeNames = ref<Array<number>>([]);
const filter_tag = ref<number>(0)
const changeFlag = ref<boolean>(false)


const searchList = ref<search>()
const getsearchListData = async () => {
    let data = await getSearchList()
    searchList.value = data
}
getsearchListData()
const goBack = () => {
    history.back()
}

let value = ref<string>('');

const start = () => {
    //finish error
    if (value.value) {
        LoadingBar.start()
        lookResult(value.value)
    } else {
        Dialog("请输入内容")
    }
}
const getSearchSuggestResult = ref<searchSuggest | null>(null);
const debouncedSearch = _.debounce((query: string) => {
    handelSearch(query)
}, 1000)

const handelSearch = async (query: string) => {
    if (!query) {
        // 如果query为空，提前返回
        getSearchSuggestResult.value = null;
        return;
    }

    let data = await getSearchSuggest(query);
    // console.log(data);
    getSearchSuggestResult.value = data;
};
onMounted(function () {
    // 当组件加载完后，开始监听input事件  
    value.value = ''
    const handleInput = (event: Event) => {
        const target = event.target as HTMLInputElement;
        value.value = target.value;

        debouncedSearch(target.value);
    }
    const inputElement = document.querySelector<HTMLInputElement>('.searchBox input')!; //   
    inputElement.addEventListener('input', handleInput);
})

// let showDiscover = ref<boolean>(true)
let showResult = ref<boolean>(false)

const showSuggestList = computed(() => {
    if (value.value && !showResult.value) {
        return true
    } else {
        return false
    }
})
const showTotal = computed(() => {
    if (!showSuggestList.value && !showResult.value) {
        return true
    } else {
        return false
    }
})


const getFocus = () => {
    showResult.value = false

}

let resultData = ref<searchResult>()
const totalData = ref<searchResult>()
const lookResult = async (values: string) => {

    sethistory.setHistory(values)
    LoadingBar.start()
    value.value = values
    if (!changeFlag.value) {
        let data = await getSearchResult(value.value, size.value)
        if (data) {
            LoadingBar.finish()
        }

        if (data.data.list_v2?.length == 0 || !data.data.list_v2?.length) {
            loading.value = false
            finished.value = true
        }
        totalData.value = data
        resultData.value = totalData.value

    } else {
        let data = await getOptionsData(value.value, size.value, optionsAll.value!, filter_tag.value!)
        console.log(data);

        if (data) {
            LoadingBar.finish()
            loading.value = true
            finished.value = false
        }

        if (data.data.list_v2?.length == 0) {
            loading.value = false
            finished.value = true
        }
        totalData.value = data
        resultData.value = totalData.value
    }

    showResult.value = true
    if (!flag.value) {
        flag.value = true
        scorll.value.addEventListener('scroll', () => {

            if (scorll.value.scrollTop + 760 > son.value.offsetHeight) {
                load()
            }
        });
    }


}
const showTotalResult = () => {
    if (totalData.value?.data.list_v2) {
        let sortedData = totalData.value.data.list_v2
        let data = sortedData.slice().sort((b, a) => {
            // 根据 release_date 进行排序
            const dateA: Date = new Date(a.body.release_date);
            const dateB: Date = new Date(b.body.release_date);
            return dateB.getTime() - dateA.getTime();
        });
        if (resultData.value) {
            resultData.value.data.list_v2 = data
        }
    }
}
const showNewResult = () => {
    if (totalData.value?.data.list_v2) {
        let sortedData = totalData.value.data.list_v2
        let data = sortedData.slice().sort((a, b) => {
            // 根据 release_date 进行排序
            const dateA: Date = new Date(a.body.release_date);
            const dateB: Date = new Date(b.body.release_date);
            return dateB.getTime() - dateA.getTime();
        });
        if (resultData.value) {
            resultData.value.data.list_v2 = data
        }
    }
};

const salesVolume = () => {
    if (totalData.value?.data.list_v2) {
        let sortedData = totalData.value.data.list_v2
        let data = sortedData.slice().sort((a, b) => {
            // 根据 release_date 进行排序
            const dateA: number = a.body.sort
            const dateB: number = b.body.sort;
            return dateB - dateA;
        });

        if (resultData.value) {
            resultData.value.data.list_v2 = data
        }
    }
}
const descendingOrder = () => {
    if (totalData.value?.data.list_v2) {
        let sortedData = totalData.value.data.list_v2
        let data = sortedData.slice().sort((a, b) => {
            // 根据 release_date 进行排序
            const dateA: number = a.body.price
            const dateB: number = b.body.price;
            return dateA - dateB;
        });

        if (resultData.value) {
            resultData.value.data.list_v2 = data
        }
    }
}
const ascendingOrder = () => {
    if (totalData.value?.data.list_v2) {
        let sortedData = totalData.value.data.list_v2
        let data = sortedData.slice().sort((a, b) => {
            // 根据 release_date 进行排序
            const dateA: number = a.body.price
            const dateB: number = b.body.price;
            return dateB - dateA;
        });

        if (resultData.value) {
            resultData.value.data.list_v2 = data
        }
    }
}
const load = () => {
    oldData.value = totalData.value
    if (value.value && !finished.value) {
        size.value += 20
        loading.value = true
        if (size.value == 60) {
            size.value = 40
            return
        }
        lookResult(value.value)

        setTimeout(() => {
            if (oldData.value?.data.list_v2.length == totalData.value?.data.list_v2.length) {
                loading.value = false
                finished.value = true
                changeFlag.value = false
            }
        }, 2000);

    }

}




const isActive = (index: number) => {
    return activeNames.value.includes(index);
};

const handleCollapseChange = (index: number) => {
    if (isActive(index)) {
        activeNames.value = activeNames.value.filter((item) => item !== index);
    } else {
        activeNames.value.push(index);
    }
};

const selectArr = ref<Array<parpams>>()
let optionsAll = ref<TotalOptions>()

const reset = () => {
    optionsAll.value = {
        class_name: '',
        class_parameters: [
            {
                parameter_name: '',
                rules: [
                    {
                        name: ''
                    }
                ]
            }
        ]
    }

    if (selectArr.value?.length) {
        for (let j = 0; j < selectArr.value!.length; j++) {
            for (let k = 0; k < selectArr.value![j].rules.length; k++) {
                selectArr.value![j].rules[k].checked = false
            }
        }
    }
    filter_tag.value = 0

}


let selectOptions = ref<Array<parameter>>()


//点击选中第一序列
const selectSon = (checked: boolean, name: string, arr: Array<parpams>) => {
    checked = true
    reset()
    optionsAll.value!.class_name = name;

    selectArr.value = arr
    if (totalData.value) {

        for (let i = 0; i < totalData.value?.data.classes.length; i++) {
            if (totalData.value.data.classes[i].class_name == name) {
                totalData.value.data.classes[i].checked = checked
            } else {
                totalData.value.data.classes[i].checked = false
            }
        }

    }

    selectOptions.value = [
        {
            parameter_name: '',
            rules: [
                {
                    name: ''
                }
            ]
        }
    ]


}



const selectSonBtn = (parameterName: string, name: string, checked: boolean) => {
    for (let j = 0; j < selectArr.value!.length; j++) {
        for (let k = 0; k < selectArr.value![j].rules.length; k++) {
            if (selectArr.value![j].rules[k].name == name) {
                selectArr.value![j].rules[k].checked = !checked
            }
        }

    }

    let tempArr = [...selectOptions.value!]
    for (let i = 0; i < selectOptions.value!.length; i++) {
        if (selectOptions.value![i].rules![0].name == name) {
            selectOptions.value!.splice(i, 1)
            return
        }
        if (!selectOptions.value![i].rules![0].name) {
            selectOptions.value!.splice(i, 1)
        }
    }

    let selectObj = ref<parameter>()

    selectObj.value = {
        parameter_name: parameterName,
        rules: [
            {
                name: name
            }
        ]
    }

    tempArr.push(selectObj.value)

    selectOptions.value = tempArr
    optionsAll.value!.class_parameters = selectOptions.value
    // console.log(optionsAll.value);
}



const selectValue = (value: number) => {
    filter_tag.value = value
}
const confirm = () => {
    console.log(optionsAll.value);
    changeFlag.value = true
    lookResult(value.value)
    right.value = false

}

const screening = () => {
    console.log(totalData.value);

    if (totalData.value?.data.list_v2) {

        right.value = true
        return
    }
    Dialog("没有数据")
}
const recommendArr = ref<Recommend>()

const recommendData = async () => {
    let data = await recommend()
    console.log(data);

    recommendArr.value = data

}
recommendData()

</script>
<template>
    <div class="box">
        <div class="tabNav">
            <div class="back"><van-icon name="arrow-left" @click="goBack" /></div>
            <div class="searchBox"><input v-model.trim="value" placeholder="请输入搜索商品名称" @focus="getFocus"
                    @input="debouncedSearch(value)" /></div>
            <div class="btn"><van-icon name="search" @click="start" /> </div>
        </div>
        <!-- 搜索发现 -->
        <div class="discoverList" v-show="showTotal">

            <div class="history" v-if="sethistory.historyArr.length > 0">
                <h3 class="historyTitle"><span>搜索历史</span><span> <var-icon @click="sethistory.clearHistory"
                            name="trash-can-outline" /></span></h3>
                <div class="historyList">
                    <span v-for="item in sethistory.historyArr" :key="item" @click="lookResult(item)">{{ item }}</span>
                </div>
            </div>
            <h3>搜索发现</h3>
            <div class="list">
                <div class="listItem" v-for="item in searchList?.discover_list" :key="item.id"
                    @click="lookResult(item.desc)">{{ item.desc }}</div>
            </div>
        </div>

        <div class="suggestList" v-show="showSuggestList">
            <div @click="lookResult(item.title)" v-for="item in getSearchSuggestResult?.data.list ">{{ item.title }}</div>
        </div>
        <div class="searchResult" v-show="showResult">
            <div class="selectTab">
                <var-tabs v-model:active="active" color="#f2f2f2" offset-y="2px">
                    <var-tab>
                        <var-menu-select v-model="selectOneValue" placement=bottom size="large">
                            <span class="selectBtn" type="primary">{{ selectOneValue ? selectOneValue : '综合' }}<var-icon
                                    name="menu-down" /></span>

                            <template #options>
                                <var-menu-option @click="showTotalResult" label="综合"><span>综合排序</span></var-menu-option>
                                <var-menu-option @click="showNewResult" label="新品"><span>新品优先</span></var-menu-option>
                            </template>
                        </var-menu-select>
                    </var-tab>
                    <var-tab @click="salesVolume">销量</var-tab>
                    <var-tab>
                        <var-menu-select v-model="sort" placement=bottom size="large">
                            <span class="selectBtn" type="primary">价格<var-icon name="menu-down" /></span>

                            <template #options>
                                <var-menu-option @click="ascendingOrder" label="综合">升序</var-menu-option>
                                <var-menu-option @click="descendingOrder" label="新品">降序</var-menu-option>
                            </template>
                        </var-menu-select>
                    </var-tab>
                    <div class="sx" @click="screening">筛选</div>

                </var-tabs>
                <var-popup position="right" v-model:show="right">
                    <div class="popup-example-block">
                        <div class="serveBox">
                            <div class="serveTitle">
                                <span>服务</span><span class="address">配送至浙江宁波</span>
                            </div>
                            <div class="serveSelect">
                                <span v-for="item in totalData?.data.filter_tags"
                                    :class="{ active: filter_tag == item.value }" :key="item.value"
                                    @click="selectValue(item.value)">{{ item.name }}</span>
                            </div>
                        </div>
                        <div class="classification avis">

                            <van-collapse v-model="activeNames" :border=false>
                                <div class="listSelect"> <span v-for="item in  totalData?.data.classes.slice(0, 3) "
                                        @click="selectSon(item.checked, item.class_name, item.class_parameters)"
                                        :class="{ active: item.checked }" :key="item.class_id">{{
                                            item.class_name }}</span></div>
                                <van-collapse-item title="分类" name="1">
                                    <div class="listSelectBox">
                                        <span v-for="item in  totalData?.data.classes.slice(3) "
                                            @click="selectSon(item.checked, item.class_name, item.class_parameters)"
                                            :class="{ active: item.checked }" :key="item.class_id">{{
                                                item.class_name }}</span>
                                    </div>
                                </van-collapse-item>

                            </van-collapse>
                        </div>
                        <div class="classification abis" v-for="(item, index) in selectArr" :key="item.parameter_id">

                            <van-collapse v-model="activeNames" :border=false @change="handleCollapseChange(index)">
                                <div class="listSelect" v-if="selectArr"> <span
                                        v-for="b in selectArr[index].rules.slice(0, 3) " :key="b.name"
                                        @click="selectSonBtn(item.parameter_name, b.name, b.checked)"
                                        :class="{ active: b.checked }">{{
                                            b.name }}</span></div>
                                <van-collapse-item :title="item.parameter_name" :name=item.parameter_name>
                                    <div class="listSelectBox" v-if="selectArr">
                                        <span v-for="b in selectArr[index].rules.slice(3) " :key="b.name"
                                            @click="selectSonBtn(item.parameter_name, b.name, b.checked)"
                                            :class="{ active: b.checked }">{{
                                                b.name }}</span>
                                    </div>
                                </van-collapse-item>

                            </van-collapse>
                        </div>

                        <div class="submit">
                            <span class="reset" @click="reset">重置</span><span class="confirm" @click="confirm">确认</span>
                        </div>
                    </div>

                </var-popup>
            </div>
            <div class="showResult" ref="scorll">
                <div class="list" ref="son">
                    <var-list :finished="finished" v-model:loading="loading" @load="load" loading-text="正在努力输出"
                        finished-text="一滴都没有了" error-text="出错了出错了">
                        <var-cell v-for="item in  resultData?.data.list_v2 " :key="item.body.real_product_id"
                            class="resultItem">

                            <div class="resultItem">
                                <div class="pic">
                                    <router-link :to="{ name: 'info', params: { id: item.body.product_id } }">
                                        <img :src="item.body.image" alt=""></router-link>

                                </div>
                                <div class="resultDesc">
                                    <h3>{{ item.body.name }}</h3>
                                    <div class="desc" v-html="item.body.desc"></div>
                                    <div class="functionBox">
                                        <div class="function" v-for=" i  in  item.body.class_parameters?.list "
                                            :key="i.parameter_id">
                                            <div>
                                                <div>{{ i.top_title }}</div>
                                                <div class="icon">
                                                    <img :src="i.icon" alt="">
                                                </div>
                                                <div class="value">{{ i.value }}</div>
                                            </div>
                                        </div>

                                    </div>
                                    <div class="price">￥{{ item.body.price }} <span class="sb"
                                            v-if="item.body.is_multi_price">起</span>
                                        <del class="oldPrice" v-if="item.body.market_price">{{ item.body.market_price
                                        }}</del>
                                        <img v-for=" i  in  item.body.sale_label?.activity_label " :src="i.img_url"
                                            style="width: 50px; height: 13px;">
                                    </div>
                                    <div class="score" v-if="item.body.comments_total">
                                        {{ item.body.comments_total }}评价 {{ item.body.satisfy_per }}满意
                                    </div>
                                </div>
                            </div>

                        </var-cell>

                    </var-list>


                </div>
                <var-divider description="商品推荐" />
                <div class="RecommenditemBox">
                    <div class="item" v-for="item in recommendArr?.recom_list" :key="item.action.path">
                        <div class="pic">
                            <router-link :to="{ name: 'info', params: { id: item.action.path } }">
                                <img :src='`https://${item.image_url}`'></router-link>
                        </div>
                        <p>{{ item.name }}</p>
                        <p class="price">￥{{ item.price }} <span class="old">{{ item.market_price }}</span></p>
                    </div>
                </div>

            </div>
        </div>
    </div>
</template>
<style scoped lang="scss">
.box {
    width: 100vw;
    height: 100vh;
    background-color: #ffffff;
    position: fixed;
    top: 0;
    z-index: 999;
    left: 0;
}

img {
    width: 100%;
}


.tabNav {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #f2f2f2;
    height: 46px;

    .back {
        font-size: 30px;
        color: #999;
    }

    .searchBox {
        overflow: hidden;
        width: 288px;
        height: 28px;

        input {
            border: 1px solid #e5e5e5;
            border-radius: .14rem;
            width: 100%;
            padding: 0 .5rem 0 .2rem;
            outline: 0;
            font-size: 1rem;
            font-weight: 400;
            height: 100%;
            line-height: normal;
            text-indent: 1em;
        }
    }

    .btn {
        font-size: 30px;
        color: #999;
    }
}

.historyTitle {
    display: flex;
    justify-content: space-between;

}

.historyList {
    display: flex;
    flex-wrap: wrap;

    span {
        background: rgba(0, 0, 0, .04);
        padding: 8px 12px;
        border-radius: 18px;
        height: 18px;
        line-height: 18px;
        margin: 10px;
        font-family: Helvetica Neue, Tahoma, Arial, PingFangSC-Regular, Hiragino Sans GB, Microsoft Yahei, sans-serif;
    }
}

.discoverList {
    width: 100vw;
    padding: 10px;
    box-sizing: border-box;

    .list {
        display: flex;
        flex-wrap: wrap;

        .listItem {
            width: 45vw;
            padding: 10px 0;
            color: #3c3c3c;
            font-size: 13px;
            font-family: Helvetica Neue, Tahoma, Arial, PingFangSC-Regular, Hiragino Sans GB, Microsoft Yahei, sans-serif;
        }
    }
}

.suggestList {
    width: 100vw;
    box-sizing: border-box;
    box-shadow: 1px 1px 1px 1px rgba(17, 27, 37, 0.2);

    div {
        border-bottom: 1px solid #ccc;
        padding: 0;
        margin: 0;
        height: 46px;
        font-size: 15px;

        font-family: Helvetica Neue, Tahoma, Arial, PingFangSC-Regular, Hiragino Sans GB, Microsoft Yahei, sans-serif;
        text-indent: 1rem;
        line-height: 46px;

    }
}

.selectBtn {
    display: inline-block;
    height: 46px;
    text-align: center;
    padding-top: 13px;
    box-sizing: border-box;
}

.selectTab {
    .sx {
        width: 86px;
        height: 46px;
        line-height: 46px;
        text-align: center;
        color: #646566;
    }
}

.popup-example-custom-overlay {
    background: rgba(0, 0, 0, 0.3) !important;
}

.popup-example-block {
    width: 90vw;
    position: relative;
}

.showResult {
    width: 100vw;
    height: 90vh;
    overflow: auto;
}

.resultItem {
    display: flex;
    justify-content: space-between;
    width: 100vw;
    height: 212px;
    padding: 16px 16px 16px 0;
    box-sizing: border-box;

    .pic {
        flex: 0 0 35vw;
        box-sizing: border-box;
    }

    .resultDesc {
        flex: 0 0 65vw;
        box-sizing: border-box;
        padding: 0 15px;
        font-size: 14px;
        display: flex;
        flex-direction: column;
        justify-content: center;

        h3 {
            font-size: 14px;
            font-weight: 400;
            color: rgba(0, 0, 0, .87);
            font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
        }

        .desc {
            font-size: 11px;
            height: 28px;
            color: #4a4a4a;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            display: -webkit-box;
            overflow: hidden;
        }

        .functionBox {
            margin-top: 10px;
            display: flex;
            justify-content: space-between;
            font-size: 11px;
            color: #4a4a4a;

            .icon {
                width: 24px;
                margin: 0 auto;
            }

            .function {
                width: 30%;
                text-align: center;

                .value {
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 1;
                    display: -webkit-box;
                    overflow: hidden;
                }
            }
        }

        .score {
            font-size: 11px;
            color: rgba(0, 0, 0, .54);
        }

        .price {
            color: #ff6700;
            font-size: 14px;

            .sb {
                font-size: 10px;
                display: inline-block;
                width: 16px;
                height: 16px;
                line-height: 16px;
            }

            .oldPrice {
                font-size: 11px;
                color: rgba(0, 0, 0, .54);
                padding: 0 2px;
            }
        }
    }

}

.serveBox {

    width: 90%;
    margin: 20px auto;

    .serveTitle {
        display: flex;
        justify-content: space-between;
        font-size: 15px;
        color: rgba(0, 0, 0, .54);

        .address {
            color: #ff6b00;
            font-size: 12px;
        }
    }

    .serveSelect {
        display: flex;
        justify-content: space-between;
        font-family: Helvetica Neue, Tahoma, Arial, PingFangSC-Regular, Hiragino Sans GB, Microsoft Yahei, sans-serif;
        margin-top: 20px;

        span {
            display: block;
            width: 97px;
            height: 32px;
            text-align: center;
            line-height: 32px;
            background-color: #f5f5f5;
            border-radius: 8px;
        }

        span.active {
            border: 1px solid #ff6700;
            color: #ff6700;
            background: #fde0d5;
        }
    }
}

.classification {
    position: relative;
    font-family: Helvetica Neue, Tahoma, Arial, PingFangSC-Regular, Hiragino Sans GB, Microsoft Yahei, sans-serif;


    .listSelect {
        position: absolute;
        top: 36px;

        z-index: 9999;
        width: 324px;
        left: calc(50% - 162px);
        display: flex;
        justify-content: space-between;

        span {
            display: block;
            text-align: center;
            width: 96px;
            height: 32px;
            border-radius: 8px;
            line-height: 32px;
            background-color: #f5f5f5;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            display: -webkit-box;
            overflow: hidden;
        }

        span.active {
            border: 1px solid #ff6700;
            color: #ff6700;
            background: #fde0d5;
        }
    }

    .listSelectBox {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;
        margin-top: 20px;

        span {
            display: block;
            text-align: center;
            width: 96px;
            height: 32px;
            border-radius: 8px;
            line-height: 32px;
            background-color: #f5f5f5;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            display: -webkit-box;
            overflow: hidden;
            margin-top: 10px;
        }

        span.active {
            border: 1px solid #ff6700;
            color: #ff6700;
            background: #fde0d5;
        }
    }
}

.abis {
    margin-top: 40px;
    font-size: 14px;
    color: rgba(0, 0, 0, .54);

}

.submit {
    display: flex;
    justify-content: space-between;
    overflow: hidden;
    position: fixed;
    z-index: 999999;
    bottom: 0px;

    span {
        display: block;
        width: 170px;
        height: 54px;
        line-height: 54px;
        font-size: 15px;
        font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
        text-align: center;
    }

    .reset {
        color: rgba(0, 0, 0, .87);
        background-color: white;
    }

    .confirm {
        background-color: #ff6700;
        color: #fff;
    }
}

.RecommenditemBox {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .item {
        width: 45vw;
        font-size: 14px;
        box-sizing: border-box;
        padding: 2px;

        .pic {
            width: 100%;
        }

        .price {
            color: #ff6700;

            .old {
                font-size: 10px;
                margin-left: 5px;
                color: #999;
            }
        }
    }
}
</style>